// 日志处理
const { reportLog } = require('../util/log')
const { randStr } = require('../util/random')
// 请求日志
const reqLog = async (ctx, next) => {
  // 1. 记录请求日志
  const headers = ctx.request.headers ? ctx.request.headers : null
  const body = ctx.request.body ? ctx.request.body : null
  const query = ctx.request.query ? ctx.request.query : null
  // 2. 记录请求数据
  const data = {
    headers,
    body,
    query,
    url: ctx.request.url,
    method: ctx.request.method,
    ip: ctx.request.ip,
  }
  const postData = {
    req_id: ctx.request.headers.req_id,
    module: 'reqLog',
    level: 'info',
    body: JSON.stringify(data),
  }
  // console.log(postData, '<<< postData')
  await reportLog(postData)

  await next()
}
// 响应时间
const timeLog = async (ctx, next) => {
  if (!ctx.request.headers.req_id) {
    ctx.request.headers.req_id = `${randStr(16)}${new Date().getTime()}` // 新增
  }
  const start = Date.now()
  await next() // 需要添加 await 否则第二个请求时会报错
  const end = Date.now()
  const time = end - start

  const data = {
    url: ctx.request.url,
    method: ctx.request.method,
    ip: ctx.request.ip,
    duration: time,
    start: start,
    end: end,
  }
  const postData = {
    req_id: ctx.request.headers.req_id,
    module: 'timeLog',
    level: 'info',
    body: JSON.stringify(data),
  }
  await reportLog(postData)
}

const errLog = async (ctx, next) => {
  try {
    next()
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  reqLog,
  errLog,
  timeLog,
}
